//
//  JQFYActivityViewController.m
//  JQFY
//
//  Created by apple on 2017/8/28.
//  Copyright © 2017年 yannis. All rights reserved.
//
#import "JQFYActivityViewController.h"
#import "JQFYTicketInfo_ViewController.h"
#import "JQFYAvtivityTableViewCell.h"
#import "JQFYAvtivityHeaderView.h"
#import "JQFYNetworkTool.h"
#import "JQFYTticketBannerModel.h"
#import "JQFYActivityListModel.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "JQFYActivityWebViewController.h"
#import "JQFYRhythmView.h"
#import "JQFYTicketInfoWebViewController.h"

typedef void(^ListData)(void);
@interface JQFYActivityViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,UIWebViewDelegate>
@property (nonatomic ,strong) SDCycleScrollView                 *scr;
@property (nonatomic ,strong) NSArray <JQFYTticketBannerModel *>*cycleImages;
@property (nonatomic ,copy)   NSArray <JQFYActivityListModel *> *models;
@property (nonatomic ,strong) UITableView                       *homeList;
@property (nonatomic ,copy)   NSMutableArray                    *images;
@property (nonatomic ,assign) BOOL                               isLoad;
@property (nonatomic,assign) NSUInteger pageNumber;
@property(nonatomic, strong)JQFYRhythmView *rhythmView;
@property (nonatomic,strong) ZJAnimationPopView *alert;

@end
static NSString *identifier = @"ID";
static NSString *headerViewIdentifier = @"JQFYAvtivityHeaderView";
@implementation JQFYActivityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self setupUI];
    [self setRefresh];
}

//加载数据

- (void)loadData{
    self.isLoad = YES;
    if (_cycleImages.count == 0) {
        [[[JQFYTticketBannerModel alloc] init] getCycleImage:^(NSArray *cycleImages) {
            _cycleImages = cycleImages;
            NSMutableArray *urlImages = [NSMutableArray new];
            for (JQFYTticketBannerModel *model in cycleImages) {
                [urlImages addObject:model.cover];
            }
            self.scr.imageURLStringsGroup = urlImages;
            self.isLoad = NO;
            [MBProgressHUD showWithMessage:@"加载成功"];
        } file:^{
            [MBProgressHUD showWithMessage:@"网络不给力"];
        }];
    }
    [self getModel:^{
        [MBProgressHUD showWithMessage:@"加载成功"];
    } failure:^{
        [MBProgressHUD showWithMessage:@"网络不给力"];
    }];
}

-(void)setupUI
{
    UIImage* img = [UIImage imageNamed:@"playerbg"];
    self.view.layer.contents = (id)img.CGImage;
    UIView *titView = [[UIView alloc] initWithFrame:CGRectMake(35, 0, 300, 40)];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:titView.bounds];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont fontWithName:@"Verdana-Bold" size:17];
    titleLabel.text = @"演出活动";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [titView addSubview:titleLabel];
    self.navigationItem.titleView = titView;

    //设置右边音乐动图
    self.rhythmView = [[JQFYRhythmView alloc]initWithFrame:CGRectMake(DH_Screen_Width - 40 *SCAL, 12 *SCAL, 20 *SCAL, 20 *SCAL)];
    [self.navigationController.navigationBar addSubview:self.rhythmView];
    //添加手势
    UITapGestureRecognizer *rhythmGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRhythm)];
    [self.rhythmView addGestureRecognizer:rhythmGesture];
    
    self.pageNumber = 3;
    [self setupTab];
}

//请求数据

-(void)getModel:(ListData)sussce failure:(ListData)faliure {
    [[JQFYNetworkTool sharedManager] request:RequestMethodGet urlString:@"http://app.uninhibited.cn/api/buy/ticket/list" parameters:nil finished:^(id responseObject, NSError *error) {
        if (error) {
            faliure();
        } else {
            sussce();
             NSArray *listArray = responseObject;
            if (listArray && [listArray isKindOfClass:[NSArray class]]) {
                _models = [NSArray yy_modelArrayWithClass:[JQFYActivityListModel class] json:listArray];
            }
            [self.homeList reloadData];
        }
    }];
}
//设置tab
-(void)setupTab{
    _homeList = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:_homeList];
    [_homeList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    _homeList.delegate = self;
    _homeList.dataSource = self;
    [_homeList registerClass:[JQFYAvtivityTableViewCell class] forCellReuseIdentifier:identifier];
    [_homeList registerClass:[JQFYAvtivityHeaderView class] forHeaderFooterViewReuseIdentifier:headerViewIdentifier];
    _homeList.showsVerticalScrollIndicator = NO;
    _homeList.separatorStyle = UITableViewCellSeparatorStyleNone;
    _homeList.contentInset = UIEdgeInsetsMake(0, 0, 67, 0);
    UIImage* img = [UIImage imageNamed:@"baseBG"];
    _homeList.layer.contents = (id)img.CGImage;
    //设置组头
    self.scr = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0,DH_Screen_Width, 208 *SCAL) delegate:self placeholderImage:[UIImage imageNamed:@"Electronicmusiclabel（合并）（合并）"]];
    self.scr.currentPageDotImage = [UIImage imageNamed:@"#1"];
    self.scr.pageDotImage = [UIImage imageNamed:@"#2"];
    self.scr.autoScrollTimeInterval = 4;
    self.scr.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    _homeList.tableHeaderView = self.scr;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 125 *SCAL;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        JQFYAvtivityHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerViewIdentifier];
        return headerView;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return [JQFYAvtivityHeaderView heightForView];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.models.count?self.models.count:1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JQFYAvtivityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.models[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    JQFYTicketInfo_ViewController *ticketInfo = [[JQFYTicketInfo_ViewController alloc] init];
//    ticketInfo.model = self.models[indexPath.row];
//    [self.navigationController pushViewController:ticketInfo animated:YES];
    JQFYTicketInfoWebViewController *ticketWebVc = [[JQFYTicketInfoWebViewController alloc]init];
    ticketWebVc.model = self.models[indexPath.row];
    [self.navigationController pushViewController:ticketWebVc animated:YES];

}
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
    if ([self.cycleImages[index].is_links isEqualToString:@"1"]) {
        JQFYActivityWebViewController *webController = [[JQFYActivityWebViewController alloc]init];
        NSString *urlStr = self.cycleImages[index].links;
        WKWebView *webView = [[WKWebView alloc] initWithFrame:webController.view.bounds];
        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
        [webController.view addSubview:webView];
        [self.navigationController pushViewController:webController animated:YES];
    }else{
        NSLog(@"没有连接跳转");
    }
}
#pragma mark -
#pragma mark 刷新
//设置刷新
-(void)setRefresh{
    //下拉刷新
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    [header setImages:self.images forState:MJRefreshStateIdle];
    [header setImages:self.images forState:MJRefreshStatePulling];
    [header setImages:self.images forState:MJRefreshStateRefreshing];
    self.homeList.mj_header = header;
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    //上拉加载
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    [footer setImages:self.images forState:MJRefreshStateRefreshing];
    self.homeList.mj_footer = footer;
    footer.refreshingTitleHidden = YES;
    [footer setTitle:@"上拉加载更多" forState:MJRefreshStateIdle];
}
//下拉刷新
-(void)refresh{
    [self.homeList.mj_header beginRefreshing];
    [self loadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.homeList.mj_header endRefreshing];
        [self.homeList reloadData];
    });
}
//上拉加载
-(void)loadMore{
    [self.homeList.mj_footer beginRefreshing];
    [self loadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.homeList.mj_footer endRefreshing];
        [self.homeList reloadData];
    });
    
    self.pageNumber += 5;
    if (self.models.count == 0) {
        return;
    }
    if (self.pageNumber >= self.models.count) {
        self.pageNumber = self.models.count;
        self.homeList.mj_footer.hidden = YES;
    } else {
        self.homeList.mj_footer.hidden = YES;
    }
    [self.homeList reloadData];
    [self.homeList.mj_footer endRefreshing];

}

//懒加载
- (NSMutableArray *)images
{
    if (_images == nil) {
        _images = [NSMutableArray new];
        for (int i = 19; i < 24; i++) {
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"图层%zd",i]];
            [_images addObject:image];
        }
    }
    return _images;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    if (__Player__.isPlaying) {
        
        if (self.rhythmView.animation) {
            return;
        }
        [self.rhythmView beginAnimation];
    }
    if (__Player__.isPlaying == NO) {
        
        [self.rhythmView stopAnimation];
    }
}

#pragma mark - 律动条动画 -
- (void)rhythmViewAnimation:(NSNotification *)noti
{
    JQFYMusicPlayerStatus status = [noti.userInfo[kMusicPlayerStatus] integerValue];
    
    if (status == JQFYMusicPlayerStatusPlaying) {
        if (self.rhythmView.animation) {
            return;
        }
        [self.rhythmView beginAnimation];
    } else {
        [self.rhythmView stopAnimation];
    }
}
#pragma mark - 跳转播放器界面 -
-(void)tapRhythm{
    NSLog(@"点击了播放器界面");
    if (__Player__.playingSong == nil) {
        UIImageView *alertError = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"前往音乐（合并）"]];
        alertError.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
        [alertError addGestureRecognizer:tap];
        self.alert = [[ZJAnimationPopView alloc] initWithCustomView:alertError popStyle:ZJAnimationPopStyleScale dismissStyle:ZJAnimationDismissStyleScale];
        self.alert.popBGAlpha = 0.6;
        self.alert.isClickBGDismiss = YES;
        [self.alert pop];
        return;
    }
    //播放界面
    JQFYPlayViewController *playerVc = [[JQFYPlayViewController alloc] init];
    [self presentViewController:playerVc animated:YES completion:nil];
}
- (void)tap{
    [self.alert dismiss];
}
@end
